package handler

import (
	"context"
	"lab-service/post/model"
	pp "lab-service/proto/post"
)

type Post struct{}

func (p *Post) One(ctx context.Context, req *pp.PostRequest, rsp *pp.PostResponse) error {
	// model Post -> mp
	mp := &model.Post{
		Id:     req.Id,
		Module: req.Module,
	}

	err := mp.OneByModule()
	if err != nil {
		if err := mp.OneById(); err != nil {
			return err
		}
	}

	rsp.Post = &pp.OnePost{
		Id:        mp.Id,
		Enable:    mp.Enable,
		CreatedAt: mp.CreatedAt.Unix(),
		UpdatedAt: mp.UpdatedAt.Unix(),
		Title:     mp.Title,
		SubTitle:  mp.SubTitle,
		Content:   mp.Content,
		Pics:      mp.Pics,
		Module:    mp.Module,
		Author:    mp.Author,
		Like:      mp.Like,
		Uid:       mp.Uid,
	}

	return nil
}

func (p *Post) Page(ctx context.Context, req *pp.PostRequest, rsp *pp.PostResponse) error {
	// model Post -> mp
	mp := &model.Post{
		Module: req.Module,
		Enable: req.Enable,
		Uid:    req.Uid,
	}

	ps, err := mp.Page(req.PageNum, req.PageSize, req.Desc, req.Order)
	if err != nil {
		return err
	}

	for _, p := range ps {
		rsp.Posts = append(rsp.Posts, &pp.OnePost{
			Id:        p.Id,
			CreatedAt: p.CreatedAt.Unix(),
			UpdatedAt: p.UpdatedAt.Unix(),
			Title:     p.Title,
			SubTitle:  p.SubTitle,
			Author:    p.Author,
			Like:      p.Like,
			Module:    p.Module,
			Uid:       p.Uid,
			Enable:    p.Enable,
		})
	}

	rsp.Total, err = mp.Count()
	if err != nil {
		return err
	}

	rsp.PageSize = req.PageSize
	rsp.PageNum = req.PageNum

	return nil
}

func (p *Post) Create(ctx context.Context, req *pp.PostRequest, rsp *pp.PostResponse) error {
	// model Post -> mm
	mm := &model.Post{
		Title:    req.Title,
		SubTitle: req.SubTitle,
		Content:  req.Content,
		Pics:     req.Pics,
		Author:   req.Author,
		Module:   req.Module,
		Enable:   false,
		Uid:      req.Uid,
	}

	if err := mm.Create(); err != nil {
		return err
	}

	return nil
}

func (p *Post) CountMe(ctx context.Context, req *pp.PostRequest, rsp *pp.PostResponse) error {
	// model Post -> mp
	mp := &model.Post{
		Uid: req.Uid,
	}

	total, err := mp.Count()
	if err != nil {
		return err
	}

	rsp.Total = total

	return nil
}

func (p *Post) Toggle(ctx context.Context, req *pp.PostRequest, rsp *pp.PostResponse) error {
	// model Post -> mp
	mp := &model.Post{
		Id: req.Id,
	}

	if err := mp.OneById(); err != nil {
		return err
	}

	if err := mp.Toggle(); err != nil {
		return err
	}

	return nil
}
